package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.advice.LyException;

import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;

import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Boolean checkExist(String data, Integer type) {
        if (StringUtils.isBlank(data) ||(1 != type && 2 != type)){
            throw new LyException(400, "请求参数有误，请重新输入！");
        }
        String clName = null;
        switch (type){
            case 1 :
                clName = "username";
                break;
            case 2 :
                clName = "phone";
        }
        //上述条件都成立的情况下，有值返回下式
       return query().eq(clName, data).count()==1;
    }



    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String KEY_PREFIX = "user:verify:code";

    @Override
    public void sendVerifyCode(String phone) {
        Map<String, String> map = new HashMap<>();
        //封装方法
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "手机号输入错误请重新输入");
        }

        //使用Apache的工具类生成一个6位数的验证码
        String code = RandomStringUtils.randomNumeric(6);
        map.put("phone", phone);
        map.put("code", code);
        //可以使用这种方法，也可以不要浅醉
        //amqpTemplate.convertAndSend( MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME,  MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY,map);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, map);

        //存入redis中，限时5min
        this.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

    }



  @Autowired
  //spring 提供的加密算法
  private BCryptPasswordEncoder passwordEncoder;

    @Override

    public void register(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();
        //考虑健壮性的情况下，需要把时间关闭后在存入
       // redisTemplate.expire()
        //假数据
    /*    redisTemplate.opsForValue().set(KEY_PREFIX+"15055554444", "123321");*/
        //注意顺序不能颠倒
        if (!redisTemplate.hasKey(key)|| !redisTemplate.opsForValue().get(key).equals(code)){
            throw new LyException(400, "验证码输入有误或者验证码过期，请从新输入");
        }
        // 2.对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 3.写入数据库
        save(user);

        //结束后，如果此时的key还存在应该删除的

    }

    @Override
    public UserDTO queryUserNameAndPass(String username, String password) {

        //根据用户名查询
        User user = query().eq("username", username).one();
        //从加密的password中推算出盐值，然后以盐值对名文进行加密，最后进行匹配比较
        if (user == null || !passwordEncoder.matches(password, user.getPassword())){
            throw new LyException(400, "用户名或者密码输入错误，请重新输入！");
        }
        UserDTO userDTO = BeanHelper.copyProperties(user, UserDTO.class);
        return userDTO;
    }

}